﻿using DJY.Code;
using System.Web.Mvc;

namespace DJY.Web
{
    public class HandlerLoginAttribute : AuthorizeAttribute
    {
        const string NOT_LOGIN_MSG = "NOT_LOGIN";

        public bool Ignore = true;
        public HandlerLoginAttribute(bool ignore = true)
        {
            Ignore = ignore;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (Ignore == false)
            {
                return;
            }

            OperatorModel user = OperatorProvider.GetCurrent();
            if (user == null || string.IsNullOrEmpty(user.UserId))
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult() {
                        Data = AjaxResult.Fail(NOT_LOGIN_MSG),
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.HttpContext.Response.Write("<script>top.location.href = '/Login/Index';</script>");
                    filterContext.HttpContext.Response.End();
                }
            }
        }
    }
}